define(["angularAMD", 'moment'], function (angularAMD, moment) {
    angularAMD.service('B0203Service', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog','$timeout', "$mddProvider",
        function ($rootScope, $filter, $translate, config, $MMWService, $mdDialog, $timeout, $mddProvider) {
            //20180809 modify by Dustdusk for M#46665: 增加[全數下工]功能
            this.employee_wrok_set_json = function(options){
                var need_work_reason = (config.cache.sys_parameter.EmployeeWorkReason=='2'||config.cache.sys_parameter.EmployeeWorkReason=='3'); //下工是否需輸入原因
                function beforeEmpWorkSetAll(callback){
                    if(need_work_reason){
                        loadEmpWorkReason('', function(selectItem){
                            if (callback)
                                callback(selectItem.page_no);
                        });
                    }else{
                        if (callback)
                            callback();
                    }
                }
                // 20230621 modify by 文蔚 for M#137892 全數下工失敗
                $mddProvider.UseForm('B0203Service', () =>{
                    $rootScope.showConfirm($filter('translate')('B0203.all.msg.confirm'),
                        function(dialog){
                            beforeEmpWorkSetAll(function(reason_no){
                                var employeewrokset = [];
                                var now_datetime = moment().format('YYYY/MM/DD HH:mm:ss');
                                options.machine_list.forEach(function(machine){
                                    employeewrokset.push({
                                        machine_no : machine.machine_no,
                                        employee_no : config.cache.account,
                                        work_mode : 'AD',
                                        work_datetime : now_datetime,
                                        reason_no: reason_no || ''
                                    });
                                });
                                dialog.hide();
                                $MMWService.sendToServer({
                                    uri : 'ServicesSTD.Module_SYS.employee_wrok_set_process',
                                    content : {
                                        employeewrokset:employeewrokset
                                    },
                                    success : function(data){
                                        $rootScope.showToast($filter('translate')('B0203.all.msg.success'));
                                        if(options.callback)
                                            options.callback(data);
                                    }
                                });
                            });
                        }
                    );
                })
            };

            this.init = function(machineList, operator, type, feedback){
                var need_work_reason  = (config.cache.sys_parameter.EmployeeWorkReason=='2'||config.cache.sys_parameter.EmployeeWorkReason=='3'); //下工是否需輸入原因
                var work_mode = 'D';

                function beforeEmpWorkSet(dialog, callback){
                    if(need_work_reason && !dialog.operator.reason_no){
                        loadEmpWorkReason('', function(selectItem){
                            dialog.operator.reason_no = selectItem.page_no;
                            dialog.operator.reason_name_display = selectItem.page_name;
                            if (callback)
                                callback();
                        });
                    }else{
                        if (callback)
                            callback();
                    }
                }

                function search(machine_no, employee_no, feedback){
                    var content = {
                        machine_no : machine_no,
                        employee_no : employee_no,
                        report_datetime : new Date(),
                        return_type : '10'
                    };

                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_SYS.user_information_get',
                        content : content,
                        success : function(data){
                            if(feedback)
                                feedback(data);
                        }
                    });
                }

                //上工檢核
                //回傳true表示該員工有在此機台上工
                function checkOutWork(machine_no, employee_work_detail){
                    var isOnWork;
                    for(var i=0; i< employee_work_detail.length; i++){
                        if(machine_no == employee_work_detail[i].machine_no) {
                            isOnWork = true;
                            break;
                        }else{
                            isOnWork = false;
                        }
                    }
                    return isOnWork;
                }

                function addWorkItem(operator, machine, employeewrokset){
                    var msg = '';
                    if(type == 'machine'){
                        //machineList.forEach(function(machine_detail){
                            var isOnWork = false;
                            for(var i = 0; i < machine.employee_work_detail.length; i++){
                                if(operator.employee_no == machine.employee_work_detail[i].employee_no){
                                    isOnWork = true;
                                    break;
                                }
                            }
                            if(!isOnWork){
                                msg += $filter('translate')('B0203.msg.column1') + machine.machine_no + $filter('translate')('B0203.msg.column2') +operator.employee_no+ $filter('translate')('B0203.msg.column3') + '<br>';
                            }
                        //});
                    }

                    if(need_work_reason && !operator.reason_no){
                        msg += $filter('translate')('B0203.showAlert.column5') + "<br>";
                    }

                    if(msg == ''){
                        employeewrokset.push({
                            machine_no : machine.machine_no,
                            employee_no : operator.employee_no,
                            work_mode : work_mode,
                            work_datetime : new Date(),
                            reason_no : operator.reason_no || ''
                        });
                    }
                    return msg;
                }

                //上工
                function empWorkSet(dialog){
                    var msg = '';
                    var content = {
                        employeewrokset:[]
                    };

                    machineList.forEach(function(machine){
                        msg += addWorkItem(dialog.operator, machine, content.employeewrokset);
                    });
                    //console.log(content.employeewrokset);
                    if(content.employeewrokset.length > 0)
                    {
                        $MMWService.sendToServer({
                            uri : 'ServicesSTD.Module_SYS.employee_wrok_set_process',
                            content : content,
                            success : function(data){
                                $rootScope.showToast($filter('translate')('B0203.showAlert.column4'));
                                dialog.preOffWorkInfo = angular.extend({}, dialog.operator);
                                dialog.operator = {employee_no:'', reason_no: ''};
                                try{
                                    document.getElementById('employee_no').focus();
                                    if (dialog.ic_card != '') {//允许连续刷IC卡下工
                                        dialog.ic_card = '';
                                        document.getElementById('ic_card').focus();
                                    }
                                } catch(e){console.error(e);}
                                if(feedback)
                                    feedback();
                            }
                        });
                    }
                    else
                    {
                        $rootScope.showAlert(msg);
                    }
                    /*if(msg == ''){
                        //20180518 modify by 李栋 for mantis#0047068
                        $MMWService.sendToServer({
                            uri: 'ServicesSTD.Module_SYS.employee_wrok_set_process',
                            content : content,
                            success : function(data){
                                $rootScope.showToast($filter('translate')('B0203.showAlert.column4'));
                                dialog.preOffWorkInfo = angular.extend({}, dialog.operator);
                                dialog.operator = {employee_no:'', reason_no: ''};
                                try{
                                    document.getElementById('employee_no').focus();
                                    if (dialog.ic_card != '') {//允许连续刷IC卡下工
                                        dialog.ic_card = '';
                                        document.getElementById('ic_card').focus();
                                    }
                                } catch(e){console.error(e);}
                                if(feedback)
                                    feedback();
                            }
                        });
                    } else {
                        $rootScope.showAlert(msg);
                    }*/
                }

                var openDialog = function(){
                    $mddProvider.UseForm('B0203Service', () =>{
                     $mdDialog.dialog(
                        'module/moduleB/program/B02/B0203/B0203.html',
                        function(dialog){
                            return {
                                css_url:'JSplugins/angular-material-lite/template/dynamicService.tmp.css',
                                machine_no: machineList[0].machine_no,  //設備
                                machine_list:machineList,
                                operator : operator,
                                preOffWorkInfo: {},
                                type:'line',
                                need_work_reason: need_work_reason,
                                ic_card: '',  //IC卡
                                _event:{
                                    'operator.employee_no':{
                                        click: (value, event) => {
                                            dialog.searchEmp()
                                        },
                                        change: (value, event) => {
                                            dialog.searchEmp(event)
                                        }
                                    },
                                    'ic_card':{
                                        click:(value, event) => {
                                            dialog.ICCardScanner()
                                        },
                                        change: (ic_card, event) => {
                                            dialog.searchICCard(event)
                                        }
                                    },
                                    'operator.reason_name':{
                                        click: () => {
                                            loadEmpWorkReason('', function (selectItem) {
                                                dialog.operator.reason_no = selectItem.page_no;
                                                dialog.operator.reason_name_display = selectItem.page_name;
                                                empWorkSet(dialog);
                                            });
                                        }
                                    }
                                },
                                _fn: {
                                    'confirm': {
                                        click: (a,b,event) => {
                                            dialog.searchEmp()
                                        }
                                    }
                                },
                                ICCardScanner: function () {//20200723 add by linzh for M#71988
                                    $rootScope.OpenScanner({
                                        after: function (result) {
                                            $timeout(function () {
                                                dialog.ic_card = result.text;
                                                dialog.searchICCard();
                                            });
                                        },
                                        exception: function () {
                                            //目前裝置無法使用相機
                                            $rootScope.showAlert($filter('translate')('B0214.showAlert.column3'));
                                        },
                                        orientation: 'landscape'
                                    });
                                },
                                searchICCard: function (event) {//20200710 add by linzh for M#71988
                                    if (!event || event.event.keyCode == 13) {
                                        if (dialog.ic_card != '') {
                                            var content = {
                                                IcNo: dialog.ic_card
                                            }
                                            $MMWService.sendToServer({
                                                uri: 'ServicesSTD.Module_SYS.ic_card_info_get',
                                                content: content,
                                                success: function (data) {
                                                    if (data.UserNo != null && data.PassWord != null) {
                                                        dialog.operator.employee_no = data.UserNo;
                                                        dialog.searchEmp();//调用员工信息查询方法
                                                    }
                                                    else {
                                                        $rootScope.showAlert($filter('translate')('Login.error.ic_card_error'));
                                                        dialog.ic_card = '';
                                                        document.getElementById('ic_card').focus();
                                                    }
                                                },
                                                error: function (data) {
                                                    $rootScope.showAlert(data.Message);
                                                    dialog.ic_card = '';
                                                    document.getElementById('ic_card').focus();
                                                }
                                            });
                                        } else {
                                            $rootScope.showAlert($filter('translate')('B0203.showAlert.column7'));
                                            dialog.ic_card = '';
                                            document.getElementById('ic_card').focus();
                                        }
                                    }
                                },
                                searchEmp: function(event){
                                    if(!event || event.event.keyCode==13){
                                        if(dialog.operator.employee_no !== ''){
                                            //20190705 modify by Dustdusk for M#59580: 將員工編號自動大寫
                                            dialog.operator.employee_no = dialog.operator.employee_no.toUpperCase();
                                            //20220909 modify by wangzy for 0118714: 前端上下工页面，先选择上下工原因，在点击确认，被选的原因会清空，同时弹出画面要求再次选择原因
                                            var reason_no = dialog.operator.reason_no ? dialog.operator.reason_no : '';
                                            var reason_name = dialog.operator.reason_name ? dialog.operator.reason_name : '';
                                            search(dialog.machine_no, dialog.operator.employee_no, function(data){
                                                dialog.operator = data;
                                                dialog.operator.reason_no = reason_no;
                                                dialog.operator.reason_name_display = reason_name;
                                                dialog.operator.shift_end_time= new Date();
                                                if(config.setting.autoWorkset)
                                                    dialog.confirm();
                                            });
                                        } else{
                                            $rootScope.showAlert($filter('translate')('B0203.showAlert.column1'));
                                            document.getElementById('employee_no').focus();
                                        }
                                    }
                                },
                                beforeShown: function(){
                                    try{
                                         // 20231102 modify by shiwl 0149220: 贝士达：6.0 MES系统测试区，开启扫描模式后，登录界面还有上工界面光标标未定位到IC卡栏位                                                        
                                         $timeout(function(){
                                            if(config.setting.scanBarcod=="Y"){
                                                document.getElementById('ic_card').focus();
                                            } else {
                                                document.getElementById('operator.employee_no').focus();
                                            }
                                        },1000); 
                                    } catch(e){console.error(e);}
                                },
                                loadEmpWorkReason: function(){
                                    loadEmpWorkReason(dialog.operator.reason_no, function(selectItem){
                                        dialog.operator.reason_no = selectItem.page_no;
                                        dialog.operator.reason_name_display = selectItem.page_name;
                                    });
                                },
                                back: function () {
                                    this.hide();
                                },
                                confirm: function () {
                                    //是否有輸入下工人員
                                    if(dialog.operator.employee_no && dialog.operator.employee_no!='') {
                                        if(!dialog.operator.employee_work_detail){
                                            $rootScope.showAlert($filter('translate')('B0203.showAlert.column2'));
                                            document.getElementById('employee_no').focus();
                                        } else {
                                            //20170602 modify by Dustdusk for 作業區也需要檢核是否下工過
                                            //if(type=='line'){
                                                //為生產線
                                                var msg = '';
                                                var confirm;
                                                if(!checkOutWork(dialog.machine_no, dialog.operator.employee_work_detail)){
                                                    msg = $filter('translate')('B0203.showAlert.column3');
                                                    confirm = function () {
                                                        dialog.tmpOnWorkInfo = {};
                                                        dialog.operator = { employee_no: '', reason_no: '' };
                                                        if (dialog.ic_card != '') {//允许连续刷IC卡下工
                                                            dialog.ic_card = '';
                                                            document.getElementById('ic_card').focus();
                                                        } else {
                                                            document.getElementById('employee_no').focus();
                                                        }
                                                    };
                                                }
                                                //M#84747 上下工訊息不卡控
                                                beforeEmpWorkSet(dialog, function(){
                                                    empWorkSet(dialog, confirm);
                                                });
                                                /*if(msg == ''){
                                                    beforeEmpWorkSet(dialog, function(){
                                                        empWorkSet(dialog, confirm);
                                                    });
                                                } else {
                                                    $rootScope.showAlert(msg, confirm);
                                                }*/
                                            // } else {
                                            //     //為作業區
                                            //     empWorkSet(dialog);
                                            // }
                                        }
                                    }else{
                                        $rootScope.showAlert($filter('translate')('B0203.showAlert.column1'));
                                        document.getElementById('employee_no').focus();
                                    }
                                }
                            };
                        }
                    );})
                };

                if(!operator){
                    operator = {employee_no:'', reason_no: ''};
                    openDialog();
                } else {
                    search(machineList[0].machine_no, operator.employee_no,function(data){
                        operator = data;
                        operator.shift_end_time= new Date();
                        openDialog();
                    });
                }
            };

            // 人員原因基本資料取得
            function loadEmpWorkReason(reason_no, callback){
                $MMWService.pageNumberInfoGet({
                    // page_mode : '35',
                    form_name:'PageNo_27',
                    query_condition_info:[
                        {column_name:'REASONTYPE', query_mode:'0', value:'1', merge_condition_model:'AND' },
                        {column_name:'ISSUESTATE', query_mode:'0', value:'2', merge_condition_model:'AND' }
                    ]
                }, function(items){
                    if(items && items.length > 0){
                        $rootScope.showSelect({
                            label : function(item){
                                return item.page_name + '(' + item.page_no + ')';
                            },
                            title: $filter('translate')('B0203.plz_select_reason'),
                            code : 'page_no',
                            selectCode : reason_no || '',
                            list : items,
                            confirm : function(selectItem, radio_dialog){
                                radio_dialog.hide();
                                if (callback)
                                    callback(selectItem);
                            }
                        });
                    } else {
                        $rootScope.showAlert($filter('translate')('B0203.showAlert.column6'));
                    }
                });
            }
        }]);
});
